//
//  Promiss.swift
//  JKTools
//
//  Created by 姜奎 on 2025/1/3.
//

import Foundation
import Cocoa
import Security.Authorization

class AuthManager {
    static func openSystemPreferencesForFullDiskAccess() {
        let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles")!
        NSWorkspace.shared.open(url)
    }

    static func hasFullDiskAccess() -> Bool {
        let fileManager = FileManager.default
        do {
            try fileManager.contentsOfDirectory(atPath: "/")
            return true
        } catch {
            return false
        }
    }


    static func requestRootAuthorization(completion:(Bool)->Void) {
            // 使用 Authorization Services 来请求管理员权限
        var authorizationRef: AuthorizationRef?
        let status = AuthorizationCreate(nil, nil, [.extendRights, .interactionAllowed], &authorizationRef)

        if status == errAuthorizationSuccess {

                // 定义授权项的值（如果需要）
            let itemValue = "/usr/local/bin"
            let valueLength = itemValue.utf8.count
            let valuePointer = UnsafeMutablePointer<Int8>.allocate(capacity: valueLength)
            defer {
                valuePointer.deallocate()
            }
            itemValue.withCString { cString in
                valuePointer.initialize(from: cString, count: valueLength)
            }

                // 定义授权项的标志
            let itemFlags: UInt32 = AuthorizationFlags.interactionAllowed.rawValue

                // 创建 AuthorizationItem 实例
            var rights = AuthorizationItem(
                name: "com.apple.security.file.read-write",
                valueLength: valueLength,
                value: UnsafeMutableRawPointer(valuePointer),
                flags: itemFlags
            )
            var rightsSet = AuthorizationRights(count: 1, items: UnsafeMutablePointer(&rights))

            var authStatus = AuthorizationCopyRights(authorizationRef!, &rightsSet, nil, .interactionAllowed, nil)

            completion(authStatus == errAuthorizationSuccess)

            if authStatus != errAuthorizationSuccess {
                print("Authorization failed: \(authStatus)")

                    // 处理错误
                switch authStatus {
                    case errAuthorizationDenied:
                        print("User denied the authorization request.")
                    case errAuthorizationCanceled:
                        print("User canceled the authorization request.")
                    case errAuthorizationInteractionNotAllowed:
                        print("Interaction is not allowed for this authorization request.")
                    case errAuthorizationInvalidSet:
                        print("The authorization rights set is invalid.")
                    default:
                        print("Unknown authorization error: \(authStatus)")
                }
            } else {
                print("Authorization succeeded.")
            }


            AuthorizationFree(authorizationRef!, [])
        }

        
    }

    static func requestRootAuthorizationExecuteWithPrivileges(completion:(Bool)->Void) {
            // 使用 Authorization Services 来请求管理员权限
        var authorizationRef: AuthorizationRef?
        let status = AuthorizationCreate(nil, nil, [.extendRights, .interactionAllowed], &authorizationRef)

        if status == errAuthorizationSuccess {

                // 定义授权项的值（如果需要）
            let itemValue = "/usr/local/bin"
            let valueLength = itemValue.utf8.count
            let valuePointer = UnsafeMutablePointer<Int8>.allocate(capacity: valueLength)
            defer {
                valuePointer.deallocate()
            }
            itemValue.withCString { cString in
                valuePointer.initialize(from: cString, count: valueLength)
            }

                // 定义授权项的标志
            let itemFlags: UInt32 = AuthorizationFlags.interactionAllowed.rawValue

                // 创建 AuthorizationItem 实例
            var rights = AuthorizationItem(
                name: "com.apple.security.file.read-write",
                valueLength: valueLength,
                value: UnsafeMutableRawPointer(valuePointer),
                flags: itemFlags
            )
            var rightsSet = AuthorizationRights(count: 1, items: UnsafeMutablePointer(&rights))

            var authStatus = AuthorizationCopyRights(authorizationRef!, &rightsSet, nil, .interactionAllowed, nil)

            completion(authStatus == errAuthorizationSuccess)

            if authStatus != errAuthorizationSuccess {
                print("Authorization failed: \(authStatus)")

                    // 处理错误
                switch authStatus {
                    case errAuthorizationDenied:
                        print("User denied the authorization request.")
                    case errAuthorizationCanceled:
                        print("User canceled the authorization request.")
                    case errAuthorizationInteractionNotAllowed:
                        print("Interaction is not allowed for this authorization request.")
                    case errAuthorizationInvalidSet:
                        print("The authorization rights set is invalid.")
                    default:
                        print("Unknown authorization error: \(authStatus)")
                }
            } else {
                print("Authorization succeeded.")
            }


            AuthorizationFree(authorizationRef!, [])
        }


    }


        /// 执行脚本命令
        ///
        /// - Parameters:
        ///   - command: 命令行内容
        ///   - needAuthorize: 执行脚本时,是否需要 sudo 授权
        /// - Returns: 执行结果
    static func runCommand(_ command: String, needAuthorize: Bool) -> (isSuccess: Bool, executeResult: String?) {
        let scriptWithAuthorization = """
    do shell script "\(command)" with administrator privileges
    """
        
        let scriptWithoutAuthorization = """
    do shell script "\(command)"
    """
        
        let script = needAuthorize ? scriptWithAuthorization : scriptWithoutAuthorization
        let appleScript = NSAppleScript(source: script)
        
        var error: NSDictionary? = nil
        let result = appleScript!.executeAndReturnError(&error)
        if let error = error {
            print("执行 \n\(command)\n命令出错:")
            print(error)
            Alert.alert(message: "\(error)")
            return (false, nil)
        }
        
        return (true, result.stringValue)
    }

}

